<template>
    <!-- 检验检查见弹框 -->
    <el-dialog ref="checkDialog" v-if="showFlag" class="l-dialog s-lg check-dialog" :title="dialogTitle" :visible.sync="showFlag" append-to-body @close="onClose(false)" :close-on-press-escape="false" :close-on-click-modal="false">
        <el-row :gutter="24" v-loading="loading" :element-loading-text="loadingText" element-loading-background="rgba(255,255,255,.7)">
            <el-col :span="14">
                <!-- 搜索 -->
                <!-- <div class="search-bar">
                    <el-input placeholder="请输入项目名称进行添加" v-model.trim="search" maxlength="100" size="small">
                        <template slot="append" type="primary" @click="searchClass">搜索</template>
                    </el-input>
                </div> -->
                <div class="tabs-box">
                    <el-tabs v-model="activeTabId" @tab-click="toggleClassTabs">
                        <el-tab-pane v-for="(item, idx) in classData" :key="idx" :label="item.checklistClassName" :name="String(item.id)"></el-tab-pane>
                    </el-tabs>
                    <div class="tree-box">
                        <el-tree ref="classTree" :data="classTreeList" v-loading="treeLoading" node-key="id" :props="defaultProps" empty-text="暂无数据" default-expand-all :expand-on-click-node="false">
                            <span class="custom-tree-node" slot-scope="{ node, data }">
                                <span>{{ node.label }}</span>
                                <div class="handle-group" v-if="(!data.checklistClassResult || (data.checklistClassResult && data.checklistClassResult.length < 1)) && data.templateValue">
                                    <el-button type="text" size="mini" @click="onAddItem(data)">添加至意见单</el-button>
                                </div>
                            </span>
                        </el-tree>
                    </div>
                </div>
                <!-- 项目 -->
                <div class="box detail-box">
                    <div class="box-title">项目</div>
                    <div class="box-inner">
                        <el-tag class="tag-item" v-for="(tag, idx) in checkProjectArr" :key="idx" closable type="primary" disable-transitions @close="onDeleteItem(tag, idx)">
                            {{tag.checklistClassName}}
                        </el-tag>
                    </div>
                </div>
                <!-- 患者上传图片 -->
                <div class=" box img-box">
                    <div class="box-title">患者上传图片</div>
                    <div class="box-inner">
                        <template v-if="uploadImgData && uploadImgData.length > 0">
                            <div class="img-item" v-for="(item, idx) in uploadImgData" :key="idx">
                                <div v-if="item.msgContent" v-viewer>
                                    <el-image lazy style="width: 100px; height: 100px" :src="item.msgContent" fit="scale-down"></el-image>
                                </div>
                                <el-image lazy v-else style="width: 100px; height: 100px" :src="item.msgContent" fit="scale-down"></el-image>
                            </div>
                        </template>
                        <span v-else class="info-tips">暂无数据</span>
                    </div>
                </div>

            </el-col>
            <el-col :span="10">
                <div class="box device-box">
                    <h3 class="head-title">填写报告意见单</h3>
                    <div class="box-title">处理意见</div>
                    <div class="box-inner no-border">
                        <el-input class="device-input" type="textarea" resize="none" v-model.trim="processingOpinion" placeholder="请输入处理意见" maxlength="500" show-word-limit></el-input>
                    </div>
                </div>
            </el-col>
        </el-row>
        <div slot="footer" class="dialog-footer">
            <el-button size="small" class="dialog-btn" @click="onClose(false)">取消</el-button>
            <el-button size="small" type="primary" class="dialog-btn" @click="onSubmitSave">保存</el-button>
        </div>
    </el-dialog>
</template>
<script>
    export default {
        data() {
            return {
                logId: '',
                loading: false,
                loadingText: '',
                showFlag: false,
                dialogTitle: '',
                dialogHandle: 'add',
                search: '', // 搜索字段
                uploadImgData: [], // 患者上传图片数据
                patientIM:null,

                /* 选项卡 */
                classData: [], // 检验检查分类标题
                activeTabId: '1', // 选项卡active

                /* 分类树形 */
                treeLoading: false,
                classTreeList: [],
                defaultProps: {
                    children: 'list',
                    label: 'checklistClassName',
                },

                editId: '',
                processingOpinion: '', // 处理意见
                checkProjectArr: [], // 添加的项目
            }
        },
        methods: {
            /** 打开检验检查弹框
             * @params type 操作类型：add,edit
             * @params logId 问诊id
             * @params id 当前编辑的意见单id，type=edit时必传 */
            onOpen({ type, logId, id ,userIm} = {}) {
                this.showFlag = true;
                this.logId = logId;
                this.dialogHandle = type;
                this.loading = true;
                this.loadingText = '加载中';
                this.checkProjectArr = [];
                this.patientIM = userIm;

                this.editId = id || '';

                if (type == 'edit') {
                    this.dialogTitle = '编辑报告意见单';
                    this.getEditDetail(id)
                } else {
                    this.dialogTitle = '新增报告意见单';
                }

                this.getCheckTabs();
                this.getUploadImgList();

                setTimeout(() => {
                    this.loading = false;
                }, 400)
            },
            // 获取检验检查详情
            getEditDetail(id) {
                this.loading = true;
                this.loadingText = '加载中';

                this.$ajax.getInspectionOpinionDetail({ id }).then(res => {
                    this.processingOpinion = res.data.processingOpinion || '';
                    this.checkProjectArr = [];

                    if (res.data.checkProject && res.data.checkId) {
                        let idArr = res.data.checkId.split(',');
                        let nameArr = res.data.checkProject.split(',');

                        nameArr.forEach((name, index) => {
                            if (name) {
                                this.checkProjectArr.push({
                                    id: idArr[index],
                                    checklistClassName: name
                                })
                            }
                        })
                    }

                    this.loading = false;
                }).catch(err => {
                    this.loading = false;
                    this.$message.closeAll();
                    this.$message.error(err.msg);
                })
            },
            // 保存新增&编辑
            onSubmitSave() {
                if (!this.processingOpinion) {
                    this.$message.closeAll();
                    this.$message.error('请填写处理意见')
                    return false;
                }

                if (this.checkProjectArr.length < 1) {
                    this.$message.closeAll();
                    this.$message.error('请选择至少一个项目')
                    return false;
                }

                let checkNameArr = [],
                    checkIdArr = [];
                this.checkProjectArr.forEach(item => {
                    checkIdArr.push(item.id)
                    checkNameArr.push(item.checklistClassName)
                })

                let params = {
                    logId: this.logId,
                    processingOpinion: this.processingOpinion,
                    checkProject: checkNameArr.join(","),
                    checkId: checkIdArr.join(","),
                };

                let apiName = '';
                if (this.dialogHandle == 'edit') {
                    apiName = 'updateInspectionOpinion';
                    params.id = this.editId;
                } else {
                    apiName = 'addInspectionOpinion'
                }

                this.loading = true;
                this.loadingText = '保存中';
                this.$ajax[apiName](params).then(res => {
                    this.$message.closeAll();
                    this.$message({
                        type: 'success',
                        message: res.msg
                    });

                    this.loading = false;
                    this.onClose(true);
                }).catch(err => {
                    this.loading = false;
                    this.$message.closeAll();
                    this.$message({
                        type: 'error',
                        message: err.msg
                    });
                })
            },
            // 添加项目
            onAddItem(data) {
                let flag = this.checkProjectArr.filter(item => data.id == item.id)

                if (flag.length <= 0) {
                    this.checkProjectArr.push(data)
                } else {
                    this.$message.closeAll();
                    this.$message({
                        type: 'warning',
                        message: '不能重复添加项目'
                    })
                }
            },
            // 移除项目
            onDeleteItem(data, index) {
                this.checkProjectArr.splice(index, 1);
            },
            // 获取患者上传图片
            getUploadImgList() {
                this.$ajax.getChatImages({
                    logId: this.logId,
                    userIm: this.patientIM,
                }).then(res => {
                    this.uploadImgData = res.data.list || []
                })
            },
            // 获取所有分类
            getClassifyList(id) {
                let params = {
                    id: id || 1, // 0，默认查一级节点
                };
                this.treeLoading = true;
                this.$ajax.clickChecklistClass(params).then(res => {
                    let result = [];
                    let arr = res.data.list || [];

                    if (arr.length > 0) {
                        arr.forEach((o1, i1) => {
                            let temp = {
                                id: o1.id,
                                checklistClassName: o1.checklistClassName,
                                list: []
                            }

                            if (o1.list && !Array.isArray(o1.list)) {
                                temp.list = o1.list.list;
                            } else if (o1.list && Array.isArray(o1.list)) {
                                temp.list = o1.list;
                            }

                            result.push(temp);
                        })
                    }

                    this.classTreeList = result;
                    this.treeLoading = false;
                }).catch(err => {
                    this.treeLoading = false;
                    this.$message.closeAll();
                    this.$message.error(err.msg);
                    this.classTreeList = [];
                })
            },
            searchClass() {

            },
            // 切换选项卡
            toggleClassTabs() {
                this.getClassifyList(this.activeTabId);
            },
            // 获取检验检查分类(选项卡展示)
            getCheckTabs() {
                this.$ajax.getChecklistClassName().then(res => {

                    this.classData = res.data.list || [];

                    this.activeTabId = (this.classData[0] && '' + this.classData[0].id) || '0';
                    this.getClassifyList(this.activeTabId);
                }).catch(err => {
                    this.$message.closeAll();
                    this.$message.error(err.msg);

                    this.classData = [];
                })
            },
            // 关闭弹框
            onClose(flag) {
                this.showFlag = false;

                this.processingOpinion = ''; // 处理意见
                this.checkProjectArr = []; // 添加的项目

                this.$emit('closed', flag);
            },
        },
        mounted() {

        }
    }
</script>

<style lang="scss" src="./checkDialogStyle.scss"></style>